package com.probiz.estoresa.product.web.action;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.common.model.product.SkuOption;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.core.model.BaseObject;
import com.probiz.estore.product.model.SkuOptionFullyModel;
import com.probiz.estore.product.service.SkuOptionManager;
import com.probiz.estore.product.service.SkuOptionValueManager;
import com.probiz.estore.webapp.util.RequestUtil;

public class SkuOptionController extends GenericStoreAdminController<SkuOption> {
    private SkuOptionManager skuOptionManager = null;
    private SkuOptionValueManager skuOptionValueManager = null;

    public void setSkuOptionManager(SkuOptionManager inMgr) {
        this.skuOptionManager = inMgr;
    }
    

	public void setSkuOptionValueManager(SkuOptionValueManager skuOptionValueManager) {
		this.skuOptionValueManager = skuOptionValueManager;
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericController#getEntityName(java.lang.Object)
	 */
	@Override
	protected String getEntityName(SkuOption entity) {
		return entity.getSkuOptionName();
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.BaseController#initController()
	 */
	@Override
	protected void initController() throws Exception {
		mgr = skuOptionManager;
	}
	
	@Override
	protected Map<String,String> getSortMap(){
		Map<String,String> sortMap = new HashMap<String,String>();
		sortMap.put("1", "convert_gbk(skuOptionName)");
		sortMap.put("2", "convert_gbk(memo)");
		return sortMap;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericController#preSave(javax.servlet.http.HttpServletRequest,
	 *      java.lang.Object, org.springframework.validation.BindException)
	 */
	@Override
	protected void preSave(HttpServletRequest request, SkuOption entity, BindException errors) {
		
	}

    @Override
    public ModelAndView save(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 取得Form对应的Model
		SkuOption entity = formBackingObject(request);

		BindException errors = null;
        Map<String, Object> data = new HashMap<String, Object>();
		try {
			ServletRequestDataBinder binder = bindAndValidate(request, entity);
			errors = new BindException(binder.getBindingResult());
			// 传给子类的实现，后者可以继续验证和加入错误到errors
			preSave(request, entity, errors);
			if (!errors.hasErrors()) {// 里面如果出错应该抛出异常
				Map<String, Object> saveData = skuOptionManager
						.saveFully(getProductFullyModel(request, entity, data));
				data.putAll(saveData);  //这里页面返回由于不是用JSON返回，所以回传的id值可以不处理。
				postSave(request, entity);
			}
		} catch (ApplicationException e) {
			handleApplicationException(errors, e);
		}

		ModelAndView mav;
		if (errors.hasErrors()) {
			mav = showForm(request, errors);
		} else if (successView != null) {
			mav = getModelAndView(successView, errors.getModel());
		} else {
			mav = getRedirectToActionView("edit", ((BaseObject) entity).getId()
					.toString());
		}
		return mav;
    }

    // 构造商品规格模型，方便保存
	private SkuOptionFullyModel getProductFullyModel(HttpServletRequest request,
			SkuOption skuOption, Map<String, Object> data) {
        SkuOptionFullyModel model = new SkuOptionFullyModel();
        model.setSkuOption(skuOption);

        // ---------- start:绑定规格值--------------
		String[] ids = (String[]) ArrayUtils.clone(RequestUtil
				.getParameterValuesNullSafe(request, "skuOptionValueIds"));
		String[] names = RequestUtil.getParameterValuesNullSafe(request,
				"skuOptionValueNames");
		String[] types = RequestUtil.getParameterValuesNullSafe(request,
				"skuOptionValueTypes");
		String[] values = RequestUtil.getParameterValuesNullSafe(request,
				"skuOptionValueValues");

		// 传入返回map
		data.put("oldSkuOptionValueIds", ids);
		String[] newOrUpdateSkuOptionValueIds = (String[]) ArrayUtils.clone(ids);// 这里复制是为了可以在不改变request中的数据
		for (int i = 0; i < newOrUpdateSkuOptionValueIds.length; i++) {
			if (newOrUpdateSkuOptionValueIds[i].contains("new")) {
				// case:规格值是新增的
				newOrUpdateSkuOptionValueIds[i] = "";
			} else {
				// case:规格值已存在
				newOrUpdateSkuOptionValueIds[i] = ids[i].substring(ids[i]
						.indexOf("_") + 1);
			}
		}
        model.setSkuOptionValueIds(newOrUpdateSkuOptionValueIds);
		model.setSkuOptionValueNames(names);
        model.setSkuOptionValueTypes(types);
        model.setSkuOptionValueValues(values);
		// --------- end:绑定规格值----------------
        return model;
    }
	/**
	 * 删除规格值检查
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView deleteSkuOptionValueCheck(HttpServletRequest request,HttpServletResponse response) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		Long size = skuOptionValueManager.getSizeOfProductSkuOptionValue(RequestUtil.getInteger(request, "skuOptionValueId"));
		if(size > 0){
			data.put("result", "0");
		}else{
			data.put("skuOptionValueId", RequestUtil.getInteger(request, "skuOptionValueId"));
			data.put("result", "1");
		}
		return getModelAndAjaxJsonView(data);
	}
	
	
	/**
	 * 删除一条记录。并在应用级出错的时候显示出错信息。
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 取得Form对应的Model。因为要先保存其名称，否则可能会连I18N数据也已经删除了；另外可以用于出错的时候恢复显示Form页面
		SkuOption entity = formBackingObject(request);
		try {
			// 删除并设置信息
			String entityId = request.getParameter(entityIdName);
			if (!StringUtils.isEmpty(entityId)) {
				// 先构造提示信息，否则信息对应的记录可能也会被删除。
				String entityName = getEntityName(entity);
				entity = skuOptionManager.getById(new Integer(entityId));
				short deleteStatus = skuOptionManager.deleteFully(new Integer(entityId));
				String message = "";
				if(SkuOptionManager.DELETE_STATUS_TRUE.equals(deleteStatus)){
					message = getMessage("common.deleted", new Object[] {
							getEntityTypeMessage(), entityName });
					saveMessage(request, message);
					
				}else{
					message = getMessage("skuOption.delete.false", new Object[] {
							getEntityTypeMessage(), entityName });
					Map<String,Object> map = new HashMap<String,Object>();
					map.put("skuOption", entity);
					saveErrorMessage(request, message);
					return getModelAndView(formView, map);
				}
				
				
			} else {
				saveMessage(request, getMessage("errors.invalid.delete.id",
						new Object[] { entityId }));
			}
		} catch (ApplicationException e) {
			// 为了出错的时候可以恢复表单显示，构造errors。无须作表单绑定和验证
			ServletRequestDataBinder binder = this.getDefaultBinder(request,entity);
			BindException errors = new BindException(binder.getBindingResult());
			handleApplicationException(errors, e);
			
			return showForm(request, errors);
		}

		return getModelAndView(cancelFormView, null);
	}
	
	public ModelAndView multiDelete(HttpServletRequest request,
			HttpServletResponse response) {
		// 取得要删除的记录的id的列表。注意：选择框的id要是"multiIds"。
		String[] ids = request.getParameterValues("multiIds");
		if (ids != null && ids.length > 0) {
			for(String entityId :ids){
				SkuOption entity = skuOptionManager.getById(new Integer(entityId));
				short deleteStatus = skuOptionManager.deleteFully(new Integer(entityId));
				String message = "";
				if(SkuOptionManager.DELETE_STATUS_TRUE.equals(deleteStatus)){
					message = getMessage("common.deleted", new Object[] {getEntityTypeMessage(), entity.getSkuOptionName() });
					saveMessage(request, message);
					
				}else{
					message = getMessage("skuOption.delete.false", new Object[] {getEntityTypeMessage(), entity.getSkuOptionName() });
					saveErrorMessage(request, message);
				}
			}
		}
		return getRedirectToActionView("search");
	}
}
